<template>
  <view>
    <van-search
      v-model="seachKey"
      placeholder="请输入课程名称查询"
      @search="onSearch"
    ></van-search>
    <scroll-view class="list-box" scroll-y @scrolltolower="toLower">
      <list-card v-for="item in list" :key="item.id" :item="item" />
      <van-empty
        v-if="!list.length"
        :description="isLogin ? '暂无数据' : '请先到个人中心页面进行登录'"
      />
    </scroll-view>
  </view>
</template>

<script>
import ListCard from "@/components/Card/index.vue";
import { QueryCoursePage } from "@/api/course/course.js";
import { wxLogin } from "@/api/login/login.js";
export default {
  components: {
    ListCard,
  },
  data() {
    return {
      showStudentNumber: false,
      studentNumber: "",
      isLogin: false,
      total: 0,
      searchForm: {
        courseName: "",
        pageCurrent: 1,
        pageSize: 15,
      },
      list: [],
    };
  },
  onLoad() {},
  onShow() {
    this.isLogin = uni.getStorageSync("isLogin");
    if (this.isLogin && uni.getStorageSync("allowLogin")) {
      this.searchForm.pageCurrent = 1;
      this.list = [];
      this.getList();
    }
  },
  methods: {
    toLower() {
      if (this.searchForm.pageCurrent < this.total) {
        this.searchForm.pageCurrent += 1;
        this.getList();
      }
    },
    getList() {
      QueryCoursePage(this.searchForm).then((res) => {
        if (res.code === 200) {
          this.list = this.list.concat(res.data.list);
          this.total = res.data.totalPage;
        }
      });
    },
    onSearch(e) {
      this.searchForm.courseName = e.detail;
      this.list = [];
      this.searchForm.pageCurrent = 1;
      this.getList();
    },
  },
  created() {
    if (!uni.getStorageSync("isLogin")) {
      uni.login({
        provider: "weixin",
        success: async (loginRes) => {
          const res = await wxLogin({
            code: loginRes.code,
            loginAuthType: 3,
            clientType: 3,
          });
          if (res.code === 200) {
            uni.setStorageSync("isLogin", true);
            uni.setStorageSync("token", res.data.token);
            uni.setStorageSync("userInfo", res.data);
          }
        },
      });
    }
  },
};
</script>

<style>
.list-box {
  width: calc(100vw - 40rpx);
  padding: 0 20rpx;
  height: calc(100vh - 140rpx);
}
</style>
